# gozerbot/plugs/plug.py
#
#

# gozerbot imports
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plugins import plugins
from gozerbot.utils.exception import exceptionmsg, handle_exception
from gozerbot.gozerimport import gozer_import 
from gozerbot.tests import tests
from gozerbot.config import config

import os

def handle_plugenable(bot, ievent):

    """ enable and reload a plugin. """

    doall = False
    plugs = []
    oldplugs = []
    alchemyplugs = []

    if '-a' in ievent.optionset:
        doall = True

    if not ievent.rest and not doall:
        ievent.missing('<plugname>')
        return

    if doall:
        if config.get('db_driver') == "olddb":
            try:
                oldplugs = gozer_import('gplugs.olddb').__plugs__
            except ImportError:
                pass
        else:
            try:
                alchemyplugs = gozer_import('gplugs.alchemy').__plugs__
            except ImportError:
                pass

        try:
            plugs.extend(gozer_import('gplugs').__plugs__)
        except ImportError:
            pass

        if hasattr(os, 'isdir') and os.isdir('myplugs'):
            for plugname in os.listdir('myplugs'):
                if plugname.endswith('.py'):
                    plugs.append(plugname)
 
    else:
        plugs = ievent.rest.split()

    ievent.reply("trying to reload: ", plugs, dot=True)
    errors = []
    reloaded = []
    failed = []

    if config.get('db_driver') == "olddb":
        for plug in oldplugs:
            try:
                reloaded.extend(plugins.reload('gplugs.olddb', plug))
            except ImportError, ex: pass
    else:
        for plug in alchemyplugs:
            try:
                reloaded.extend(plugins.reload('gplugs.alchemy', plug))
            except ImportError, ex: pass

    if True:
        for plug in plugs: 
            try:
                reloaded.extend(plugins.reload('gplugs', plug))
            except ImportError, ex:
                try:
                    reloaded.extend(plugins.reload('myplugs', plug))
                except ImportError, ex: pass
                except Exception, ex:
                    failed.append(plug)
                    errors.append(str(ex))
            except Exception, ex:
                handle_exception()
                errors.append(exceptionmsg())
                failed.append(plug)

    ievent.reply('enabled plugins: ', reloaded, dot=True)
  
    if failed:
        ievent.reply('failed to reload: ', failed, dot=True)

    if errors:
        ievent.reply('errors: ', errors, dot=True)

    config.save()
  
cmnds.add('plug-enable', handle_plugenable, 'OPER', options={'-a': ''}, threaded=True)
examples.add('plug-enable', 'enable a plugin', 'plug-enable karma')
tests.add('plug-enable country', 'country')

def handle_plugdisable(bot, ievent):

    """ disable and unload a plugin. """

    if not ievent.rest:
        ievent.missing('<plugname>')
        return

    plugs = ievent.rest.split()
    disabled = []

    for plug in plugs:
        plugins.unload(plug)
        plugins.disable(plug)
        disabled.append(plug)

    ievent.reply('disabled plugins: ', disabled)

cmnds.add('plug-disable', handle_plugdisable, 'OPER')
examples.add('plug-disable', 'disable a plugin', 'plug-disable karma')
tests.add('plug-disable country', 'country')
